package com.github.xuemingyu.springboot.acticitycloud.service.impl;

import com.bidanet.bdcms.core.vo.Page;
import com.bidanet.hibernate.lambda.core.LambdaCriteria;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.github.xuemingyu.springboot.acticitycloud.common.Common;
import com.github.xuemingyu.springboot.acticitycloud.dao.ActivityDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.SakuraEntryFormDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.SakuraSignDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.UserInfoDao;
import com.github.xuemingyu.springboot.acticitycloud.driver.dingtalk.DingTalkService;
import com.github.xuemingyu.springboot.acticitycloud.entity.Activity;
import com.github.xuemingyu.springboot.acticitycloud.entity.SakuraEntryForm;
import com.github.xuemingyu.springboot.acticitycloud.entity.SakuraSign;
import com.github.xuemingyu.springboot.acticitycloud.entity.UserInfo;
import com.github.xuemingyu.springboot.acticitycloud.service.SakuraSignService;
import com.taobao.api.ApiException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: xmy
 * \* Date: 2019/1/28
 * \* Time: 13:44
 * \
 */
@Service
@Transactional
public class SakuraSignServiceImpl extends BaseServiceImpl<SakuraSign> implements SakuraSignService {
    @Autowired
    private SakuraSignDao sakuraSignDao;
    @Autowired
    private ActivityDao activityDao;
    @Autowired
    private SakuraEntryFormDao sakuraEntryFormDao;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private DingTalkService dingTalkService;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void queryLike(SakuraSign sakuraSign, Page<SakuraSign> page, String startTime, String endTime) {
        LambdaCriteria<SakuraSign> lambdaCriteria = lambdaQuery.create(SakuraSign.class);
        if (StringUtils.isNotEmpty(sakuraSign.getUserId())) {
            lambdaCriteria.eq(q -> {
                q.setUserId(sakuraSign.getUserId());
            });
        } else {
            sakuraSign.setStatus(true);
        }
        if (Objects.nonNull(sakuraSign.getStatus())) {
            lambdaCriteria.eq(q -> {
                q.setStatus(sakuraSign.getStatus());
            });
        }
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        if (StringUtils.isNotEmpty(startTime)) {
            lambdaCriteria.gte(q -> {
                q.setSignTime(startTime);
            });
        }
        if (StringUtils.isNotEmpty(endTime)) {
            lambdaCriteria.lte(q -> {
                q.setSignTime(endTime);
            });
        }
        if (StringUtils.isNotBlank(sakuraSign.getAuditRemark())) {
            lambdaCriteria.eq(q -> {
                q.setAuditRemark(sakuraSign.getAuditRemark());
            });
        }
        List<SakuraSign> list = lambdaCriteria.orderDesc("signTime").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(list);
        page.setTotal(count);
    }

    @Override
    public void querAll(SakuraSign sakuraSign, Page<SakuraSign> page, String startTime, String endTime) {
        LambdaCriteria<SakuraSign> lambdaCriteria = lambdaQuery.create(SakuraSign.class);
        if (StringUtils.isNotBlank(sakuraSign.getName())) {
            lambdaCriteria.like(q -> {
                q.setName("%" + sakuraSign.getName() + "%");
            });
        }
        if (Objects.nonNull(sakuraSign.getStatus())) {
            lambdaCriteria.eq(q -> {
                q.setStatus(sakuraSign.getStatus());
            });
        }
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        if (StringUtils.isNotEmpty(startTime)) {
            lambdaCriteria.gte(q -> {
                q.setSignTime(startTime);
            });
        }
        if (StringUtils.isNotEmpty(endTime)) {
            lambdaCriteria.lte(q -> {
                q.setSignTime(endTime);
            });
        }
        if (StringUtils.isNotBlank(sakuraSign.getAuditRemark())) {
            lambdaCriteria.eq(q -> {
                q.setAuditRemark(sakuraSign.getAuditRemark());
            });
        }
        List<SakuraSign> list = lambdaCriteria.orderDesc("signTime").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(list);
        page.setTotal(count);
    }

    @Override
    public void insert(SakuraSign sakuraSign) {
        checkNull(sakuraSign.getActivityId(), "活动id不能为空");
        checkString(sakuraSign.getUserId(), "userId不能为空");
        checkString(sakuraSign.getSignAddr(), "签到地址不能为空");
        checkString(sakuraSign.getSignContext(), "签到内容不能为空");
        checkString(sakuraSign.getLongitude(), "经度不能为空");
        checkString(sakuraSign.getLatitude(), "纬度不能为空");
        String signTime = simpleDateFormat.format(new Date());
        sakuraSign.setSignTime(signTime);
        sakuraSign.setDeleteTag(false);
        sakuraSign.setStatus(false);
        sakuraSign.setAuditRemark("待确认");
        Activity activity = activityDao.findFirstByActivityIdAndDeleteTag(sakuraSign.getActivityId(), false);
        SakuraEntryForm s = sakuraEntryFormDao.findFirstByUserIdAndSignStatusAndActivityId(sakuraSign.getUserId(), "已报名", sakuraSign.getActivityId());
        checkNull(s, "请先报名");
        String now = simpleDateFormat1.format(new Date());
       /* if (s.getArriveTime().compareTo(now) > 0) {
            errorMsg("请在来校日期之后签到");
        }*/
        checkNull(activity, "活动不存在");
        if (signTime.compareTo(activity.getActivityStart()) < 0 || signTime.compareTo(activity.getActivityEnd()) > 0) {
            errorMsg("不在签到时间范围");
        }
        UserInfo firstByUserId = userInfoDao.findFirstByUserId(sakuraSign.getUserId());
        checkNull(firstByUserId, "用户不存在");
        sakuraSign.setName(firstByUserId.getName());
        OapiUserGetResponse info = null;
        try {
            info = dingTalkService.getUserInfoByUserId(sakuraSign.getUserId());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (info.getErrcode().equals(0L)) {
            sakuraSign.setHeadImg(info.getAvatar());
        } else {
            sakuraSign.setHeadImg("");
        }
        sakuraSignDao.save(sakuraSign);
    }

    @Override
    public void auditSign(String ids, Long state) {
        checkString(ids, "id不能为空");
        List<Long> idList = Common.getIdList(ids);
        List<SakuraSign> list = sakuraSignDao.findSakuraSignsByIdIsInAndStatus(idList, false);
        list.forEach(q -> {
            if (state.equals(0L)) {
                q.setStatus(true);
                q.setAuditRemark("已发布");
            } else if (state.equals(1L)) {
                q.setAuditRemark("已拒绝");
            }
        });

        sakuraSignDao.save(list);
    }

    @Override
    public void delete(Long id) {
        SakuraSign one = sakuraSignDao.findOne(id);
        one.setDeleteTag(true);
        sakuraSignDao.save(one);
    }

    @Override
    protected JpaRepository<SakuraSign, Long> getDao() {
        return sakuraSignDao;
    }
}
